﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HuChaHuRen.HeNan.XiangCheng.Common
{
    public class JsonUtil
    {

        public static bool SetConfig<T>(T cfgEntity, string fileFullName)
        {
            string jsonContent = JsonConvert.SerializeObject(cfgEntity);
            File.WriteAllText(fileFullName, jsonContent);
            return true;
        }

        public static T GetConfig<T>(string fileFullName)
        {
            string jsonContent = File.ReadAllText(fileFullName);
            return JsonConvert.DeserializeObject<T>(jsonContent);
        }

        public static string BetterJson(string jsonContent)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(jsonContent);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return jsonContent;
            }
        }
    }
}
